﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace BCDEditUI
{
    public class DiskPart
    {
        private static bool ProcessStart(string[] input, out string output)
        {
            ProcessStartInfo psi = new ProcessStartInfo("DiskPart.EXE");
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.UseShellExecute = false;
            psi.WindowStyle = ProcessWindowStyle.Hidden;

            Process p = Process.Start(psi);
            foreach (string i in input)
            {
                p.StandardInput.WriteLine(i);
            }

            output = p.StandardOutput.ReadToEnd();

            return true;
        }

        public static string CreateDifferencingDisk(string vhd, string parentVhd)
        {
            if (string.IsNullOrEmpty(vhd))
            {
                return "Enter a vhd file name.";
            }
            if (File.Exists(vhd))
            {
                return "File already exist.";
            }
            if (!File.Exists(parentVhd))
            {
                return "File already exist.";
            }
            if (string.IsNullOrEmpty(Helper.ParseFileName(vhd)))
            {
                return "Vhd should be on a local disk.";
            }
            if (string.IsNullOrEmpty(Helper.ParseFileName(parentVhd)))
            {
                return "Parent Vhd should be on a local disk.";
            }
            if (Helper.ParseDrive(vhd) != Helper.ParseDrive(parentVhd))
            {
                return "Vhd and Parent vhd must be on the same volume.";
            }

            string output;
            string[] input = { string.Format(@"CREATE VDISK file=""{0}"" parent=""{1}""", vhd, parentVhd),
                             "exit"};
            ProcessStart(input, out output);

            output += "\n\nFinished.\n";

            return output;
        }
    }
}
